package org.mixed.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.servlet.http.HttpServletRequest;
import org.mixed.core.domain.ApiResponse;
import org.mixed.core.domain.Constants;
import org.mixed.core.domain.SysUser;
import org.mixed.core.domain.TreeNode;
import org.mixed.core.enums.Authorization;
import org.mixed.core.interceptor.AuthorizationInterceptor;
import org.mixed.core.resource.info.GroupInfo;
import org.mixed.core.resource.Info;
import org.mixed.core.utils.IoUtils;
import org.mixed.service.MixResourceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.*;

@RestController
@RequestMapping("${mix.prefix:/mix/web}")
public class MixResourceController extends MixBaseController{
    @Autowired
    private MixResourceService resourceService;

    @PostMapping("/folder")
    public void saveFolder(String name, @RequestParam("file") MultipartFile[] files) {
        System.out.println("folder " + name);
        for (MultipartFile file : files) {
            System.out.println(file.getOriginalFilename());
        }
    }

    @PostMapping("/file")
    public void saveFile(@RequestBody Map<String, String> map) {
        System.out.println("file " + map.get("name"));
    }

    @PostMapping("/test")
    public void saveFolder(String name) {
        System.out.println("test " + name);
    }

    private TreeNode<Info> process(TreeNode<GroupInfo> groupNode, HttpServletRequest request) {
        TreeNode<Info> value = new TreeNode<>();
        value.setNode(groupNode.getNode());
        groupNode.getChildren().stream()
                .filter(it -> allowVisit(request, Authorization.VIEW, it.getNode()))
                .map(it -> process(it, request))
                .forEach(value::addChild);
        if (!Constants.ROOT_ID.equals(groupNode.getNode().getId())) {
            resourceService.listFiles(groupNode.getNode().getId()).stream()
                    .filter(it -> allowVisit(request, Authorization.VIEW, it))
//                    .map(MagicEntity::simple)
                    .map(TreeNode::new)
                    .forEach(value::addChild);
        }
        return value;
    }

    @PostMapping("/resource")
    public ApiResponse<Object> resources(HttpServletRequest request) throws JsonProcessingException {
        Map<String, TreeNode<GroupInfo>> tree = resourceService.tree();
        Map<String, TreeNode<Info>> result = new HashMap<>();
        tree.forEach((key, value) -> {
            TreeNode<Info> root = process(value, request);
            List<TreeNode<Info>> groups = root.getChildren();
//            if(groups.size() > 0){
//                List<TreeNode<Info>> nodes = groups.get(0).getChildren();
//                configuration.getMagicDynamicRegistries().stream()
//                        .filter(it -> it.getResourceStorage().folder().equals(key))
//                        .findFirst()
//                        .map(DynamicRegistry::defaultMappings)
//                        .ifPresent(mappings -> {
//                            for (Info mapping : mappings) {
//                                nodes.add(new TreeNode<>(mapping));
//                            }
//                        });
//            }
            result.put(key, root);
        });
        return ApiResponse.success(result);
    }

    @PostMapping("/resource/folder/save")
    @ResponseBody
    public ApiResponse<String> saveFolder(@RequestBody GroupInfo group, HttpServletRequest request) {
//        isTrue(allowVisit(request, Authorization.SAVE, group), PERMISSION_INVALID);
//        Resource resource = resourceService.getResource();
//        if(resource instanceof FileResource){
//            isTrue(resource.exists(), FILE_PATH_NOT_EXISTS);
//        }
        if (resourceService.saveGroup(group)) {
            return ApiResponse.success(group.getId());
        }
        return ApiResponse.success();
    }

    @PostMapping("/resource/file/{folder}/save")
    @ResponseBody
    public ApiResponse<String> saveFile(@PathVariable("folder") String folder, String auto, HttpServletRequest request) throws IOException {
        byte[] bytes = IoUtils.bytes(request.getInputStream());
        Info entity = resourceService.getStorage(folder).read(bytes);
//        isTrue(allowVisit(request, Authorization.SAVE, entity), PERMISSION_INVALID);
        // 自动保存的代码，和旧版代码对比，如果一致，则不保存，直接返回。
//        if(entity.getId() != null && "1".equals(auto)){
//            MagicEntity oldInfo = service.file(entity.getId());
//            if(oldInfo != null && Objects.equals(oldInfo, entity)){
//                return new JsonBean<>(entity.getId());
//            }
//        }
        if (resourceService.saveFile(entity)) {
            return ApiResponse.success(entity.getId());
        }
        return ApiResponse.success();
    }

    @GetMapping("/resource/file/{id}")
    public ApiResponse<Info> detail(@PathVariable("id") String id) {
        return ApiResponse.success(resourceService.file(id));
    }

    @GetMapping("/backup")
    public ApiResponse<String> backup(Long timestamp, String id) {
//        notNull(service, BACKUP_NOT_ENABLED);
//        notBlank(id, PARAMETER_INVALID);
//        notNull(timestamp, PARAMETER_INVALID);
//        Backup backup = service.backupInfo(id, timestamp);
//        MagicEntity entity = JsonUtils.readValue(backup.getContent(), MagicEntity.class);
        return ApiResponse.success(null);
    }

    @GetMapping("/backups")
    public ApiResponse<List<Object>> backups() {
        return ApiResponse.success(new ArrayList<>());
    }

    @GetMapping("/todo")
    public ApiResponse<List<Object>> todo() {
        return ApiResponse.success(new ArrayList<>());
    }
}
